#!/sbin/openrc-run

case "${RC_SVCNAME#*[.-]}" in
	jool[_-]siit)
		name="SIIT"
		description="Stateless IP/ICMP Translator"
		command="/usr/bin/jool_siit"
		kmod_name="jool_siit"
	;;
	*)
		name="NAT64"
		description="Stateful NAT64"
		kmod_name="jool"
		command="/usr/bin/jool"
	;;
esac

: ${cfgfile:="/etc/jool/$RC_SVCNAME.conf"}

required_files="$cfgfile"

depends() {
	need net
}

start_pre() {
	resolve_instance_name

	# Don't load module if it's already loaded.
	if modprobe -qn "$kmod_name" && ! modprobe -qn --first-time "$kmod_name"; then
		return 0
	fi

	ebegin "Loading $kmod_name kernel module"
	modprobe -q $kmod_name
	eend $?
}

start() {
	ebegin "Loading $name instance $instance_name"
	$command -i "$instance_name" file handle "$cfgfile"
	eend $?
}

stop_pre() {
	resolve_instance_name
}

stop() {
	case $(instance_status) in
		Running)
			ebegin "Unloading $name instance $instance_name"
			$command instance remove "$instance_name"
			eend $?
		;;
		*)
			ewarn "WARNING: $name instance $instance_name is not running"
			return 0
		;;
	esac
}

status() {
	resolve_instance_name

	case "$(instance_status)" in
		Running)
			einfo "status: running"
			return 0
		;;
		Dead)
			if service_started || service_crashed; then
				eerror "status: crashed"
				return 32
			else
				einfo "status: stopped"
				return 3
			fi
		;;
		*)
			eerror "status: error"
			$command -i "$instance_name" instance status >&2
			return 32
		;;
	esac
}

instance_status() {
	$command -i "$instance_name" instance status 2>/dev/null | head -1
}

resolve_instance_name() {
	instance_name=$(sed -En 's/.*"instance":\s*"([^"]+)".*/\1/p' "$cfgfile")

	if [ -z "$instance_name" ] && [ "${RC_SVCNAME#*[.-]}" != "$RC_SVCNAME" ]; then
		instance_name="${RC_SVCNAME#*[.-]}"
	fi
	: ${instance_name:="default"}
}
